package com.foreverwin.mes.so.controller;

import com.foreverwin.mes.core.base.FrontPage;
import com.foreverwin.mes.core.base.AjaxResult;
import com.foreverwin.mes.core.utils.CommonMethods;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.foreverwin.mes.core.utils.StringUtils;
import com.foreverwin.mes.meapi.model.Resrce;
import com.foreverwin.mes.so.dto.ShopOrderDispatchVO;
import com.foreverwin.mes.so.model.ShopOrderDispatchDetail;
import com.foreverwin.mes.so.service.ShopOrderDispatchDetailService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.foreverwin.mes.so.service.ShopOrderDispatchService;
import com.foreverwin.mes.so.model.ShopOrderDispatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * @author Syngna
 * @since 2020-02-06
 */
@Controller
@RequestMapping("/shopOrderDispatches")
public class ShopOrderDispatchController {
    private final Logger logger = LoggerFactory.getLogger(ShopOrderDispatchController.class);

    @Autowired
    public ShopOrderDispatchService shopOrderDispatchService;

    @Autowired
    public ShopOrderDispatchDetailService shopOrderDispatchDetailService;

    /**
     * 根据id查询
     *
     * @param id 主键
     * @return
     */
    @ResponseBody
    @GetMapping("/{id:.+}")
    public AjaxResult getShopOrderDispatchById(@PathVariable String id) {
        ShopOrderDispatch result;
        try {
            result = shopOrderDispatchService.selectById(id);
        } catch (Exception e) {
            logger.error("getShopOrderDispatchById -=- {}", e.toString());
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success(result);
    }

    /**
     * 查询所有数据
     *
     * @return
     */
    @ResponseBody
    @GetMapping("")
    public AjaxResult getShopOrderDispatchList(ShopOrderDispatch shopOrderDispatch) {
        List<ShopOrderDispatch> result;
        try {
            EntityWrapper<ShopOrderDispatch> EntityWrapper = new EntityWrapper<>();
            EntityWrapper.setEntity(shopOrderDispatch);
            result = shopOrderDispatchService.selectList(EntityWrapper);
        } catch (Exception e) {
            logger.error("getShopOrderDispatchList -=- {}", e.toString());
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success(result);
    }

    /**
     * 分页查询数据
     *
     * @param frontPage 分页信息
     * @return
     */
    @ResponseBody
    @GetMapping("/getShopOrderDispatchPageList")
    public AjaxResult getShopOrderDispatchPageList(FrontPage<ShopOrderDispatch> frontPage, ShopOrderDispatch shopOrderDispatch) {
        Page result;
        try {
            String site = CommonMethods.getSite();
            shopOrderDispatch.setSite(site);
            EntityWrapper<ShopOrderDispatch> EntityWrapper = new EntityWrapper<>();
            EntityWrapper.setEntity(shopOrderDispatch);
            if (frontPage.getGlobalQuery() != null && !"".equals(frontPage.getGlobalQuery().trim())) {
                //TODO modify global query
                EntityWrapper
                        .like("handle", frontPage.getGlobalQuery())
                        .or().like("site", frontPage.getGlobalQuery())
                        .or().like("shopOrder", frontPage.getGlobalQuery())
                        .or().like("itemBo", frontPage.getGlobalQuery())
                        .or().like("resrce", frontPage.getGlobalQuery())
                        .or().like("resrceBatch", frontPage.getGlobalQuery())
                        .or().like("cycleTime", frontPage.getGlobalQuery())
                        .or().like("theoryCapacity", frontPage.getGlobalQuery())
                        .or().like("dispQty", frontPage.getGlobalQuery())
                        .or().like("dispTaskNo", frontPage.getGlobalQuery())
                        .or().like("creator", frontPage.getGlobalQuery())
                        .or().like("updater", frontPage.getGlobalQuery())
                ;
            }
            result = shopOrderDispatchService.selectPage(frontPage.getPagePlus(), EntityWrapper);
        } catch (Exception e) {
            logger.error("getShopOrderDispatchPageList -=- {}", e.toString());
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success(result);
    }

    /**
     * 派工弹出工单列表查询
     *
     * @param frontPage 分页信息
     * @return
     */
    @ResponseBody
    @GetMapping("/getDispatchShopOrderPageList")
    public AjaxResult getDispatchShopOrderPage(FrontPage<ShopOrderDispatch> frontPage, ShopOrderDispatch shopOrderDispatch) {
        Page result;
        try {
            String site = CommonMethods.getSite();
            shopOrderDispatch.setSite(site);

            result = shopOrderDispatchService.selectDispatchShopOrderPage(frontPage.getPagePlus(), shopOrderDispatch);
        } catch (Exception e) {
            logger.error("getShopOrderDispatchPageList -=- {}", e.toString());
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success(result);
    }

    /**
     * 获取工单派工主信息
     *
     * @param shopOrderDispatch
     * @return
     */
    @ResponseBody
    @GetMapping("/getDispatchShopOrder")
    public AjaxResult getDispatchShopOrder(ShopOrderDispatch shopOrderDispatch) {
        ShopOrderDispatch result;
        try {
            String site = CommonMethods.getSite();
            shopOrderDispatch.setSite(site);
            result = shopOrderDispatchService.getDispatchShopOrder(shopOrderDispatch);
        } catch (Exception e) {
            logger.error("getDispatchShopOrder -=- {}", e.toString());
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success(result);
    }

    /**
     * 获取工单派工主信息
     *
     * @param shopOrder
     * @return
     */
    @ResponseBody
    @GetMapping("/listShopOrderDispatchInfo")
    public AjaxResult listShopOrderDispatchInfo(String shopOrder) {
        ShopOrderDispatchVO result = new ShopOrderDispatchVO();
        try {
            String site = CommonMethods.getSite();
            List<ShopOrderDispatch> shopOrderDispatchList = shopOrderDispatchService.listByShopOrder(site, shopOrder);
            List<ShopOrderDispatchDetail> shopOrderDispatchDetailList = shopOrderDispatchDetailService.listByShopOrder(site, shopOrder);
            result.setShopOrderDispatchList(shopOrderDispatchList);
            result.setShopOrderDispatchDetailList(shopOrderDispatchDetailList);
        } catch (Exception e) {
            logger.error("listShopOrderDispatchInfo -=- {}", e.toString());
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success(result);
    }

    @ResponseBody
    @GetMapping("/getResourceDispatchInfo")
    public AjaxResult getResourceDispatchInfo(String resrce, String itemBo) {
        Resrce result;
        try {
            String site = CommonMethods.getSite();
            result = shopOrderDispatchService.getResourceDispatchInfo(site, resrce, itemBo);

        } catch (Exception e) {
            logger.error("getResrceById -=- {}", e.toString());
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success(result);
    }

    @ResponseBody
    @GetMapping("/listVisibleByResource")
    public AjaxResult listVisibleByResource(String resrce, String itemBo) {
        List<ShopOrderDispatchDetail> result;
        try {
            String site = CommonMethods.getSite();
            result = shopOrderDispatchDetailService.listVisibleByResource(site, resrce);

        } catch (Exception e) {
            logger.error("listVisibleByResource -=- {}", e.toString());
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success(result);
    }

    @ResponseBody
    @PostMapping("/doFutureDispatch")
    public AjaxResult doFutureDispatch(@RequestBody ShopOrderDispatch shopOrderDispatch) {
        ShopOrderDispatch result = null;
        try {
            String site = CommonMethods.getSite();
            String user = CommonMethods.getUser();
            String itemBo = shopOrderDispatch.getItemBo();
            String resrce = shopOrderDispatch.getResrce();
            Resrce resrcePo = shopOrderDispatchService.getResourceDispatchInfo(site, resrce, itemBo);
            String splitPrinciple = resrcePo.getSplitPrinciple();
            /*if (!StringUtils.isNumeric(shopOrderDispatch.getDispQty())) {
                return AjaxResult.error("派工数量必须是数字");
            }*/
            shopOrderDispatch.setCreator(user);
            shopOrderDispatch.setUpdater(user);
            switch (splitPrinciple) {
                case "1":
                    result = shopOrderDispatchService.splitSimple(site, shopOrderDispatch);
                    break;
                case "2":
                    result = shopOrderDispatchService.splitByShift(site, shopOrderDispatch);
                    break;
                case "3":
                    result = shopOrderDispatchService.splitByResourceBatch(site, shopOrderDispatch);
                    break;
                default:
                    break;
            }
            shopOrderDispatchService.isResourceFree(site, shopOrderDispatch);
        } catch (Exception e) {
            logger.error("doFutureDispatch -=- {}", e.toString());
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success(result);
    }

    /**
     * 保存和修改公用
     *
     * @param shopOrderDispatchVO 传递的实体
     * @return null 失败  实体成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/_save")
    public AjaxResult shopOrderDispatchSave(@RequestBody ShopOrderDispatchVO shopOrderDispatchVO) {
        String site = CommonMethods.getSite();
        String user = CommonMethods.getUser();
        try {
            shopOrderDispatchService.saveBatch(site, user, shopOrderDispatchVO);
        } catch (Exception e) {
            logger.error("shopOrderDispatchSave -=- {}", e.toString());
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success();
    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/_release")
    public AjaxResult taskRelease(@RequestBody List<String> taskDetailHandleList) {
        String site = CommonMethods.getSite();
        String user = CommonMethods.getUser();
        String msg = "";
        try {
            msg = shopOrderDispatchDetailService.release(site, user, taskDetailHandleList);
        } catch (Exception e) {
            logger.error("taskRelease -=- {}", e.toString());
            return AjaxResult.error(e.getMessage());
        }
        return StringUtils.notBlank(msg) ? AjaxResult.error(msg) : AjaxResult.success();
    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/_revert")
    public AjaxResult taskRevert(@RequestBody List<String> taskDetailHandleList) {
        String site = CommonMethods.getSite();
        String user = CommonMethods.getUser();
        String msg = "";
        try {
            msg = shopOrderDispatchDetailService.revert(site, user, taskDetailHandleList);
        } catch (Exception e) {
            logger.error("taskRevert -=- {}", e.toString());
            return AjaxResult.error(e.getMessage());
        }
        return StringUtils.notBlank(msg) ? AjaxResult.error(msg) : AjaxResult.success();
    }

    /**
     * 根据id删除对象
     *
     * @param id 实体ID
     * @return 0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.DELETE, value = "/{id:.+}")
    public AjaxResult shopOrderDispatchDelete(@PathVariable("id") String id) {
        int count;
        try {
            count = shopOrderDispatchService.deleteById(id) ? 1 : 0;
        } catch (Exception e) {
            logger.error("shopOrderDispatchDelete -=- {}", e.toString());
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success("count: " + count);
    }

    /**
     * 批量删除对象
     *
     * @param ids 实体集合ID
     * @return 0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/_batchDelete")
    public AjaxResult removeByIds(List<String> ids) {
        int count;
        try {
            count = shopOrderDispatchService.deleteBatchIds(ids) ? 1 : 0;
        } catch (Exception e) {
            logger.error("shopOrderDispatchBatchDelete -=- {}", e.toString());
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success("count: " + count);
    }

    @ResponseBody
    @GetMapping("/listResourceByShopOrder")
    public AjaxResult listResourceByShopOrder(String shopOrder) {
        List<Resrce> resrces = null;
        try {
            String site = CommonMethods.getSite();
            resrces = shopOrderDispatchService.listResourceByShopOrder(site, shopOrder);
        } catch (Exception e) {
            logger.error("listResourceByShopOrder -=- {}", e.toString());
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success(resrces);
    }
}